<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="en">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="scheme,macro,r5rs" />










<meta name="description" content="The pattern language, used in Scheme&amp;#39;s macro transformer specifications, is a convenient tool for writing macros. It makes Scheme users&amp;#39; lives easier, while implementing the pattern language i">
<meta name="keywords" content="scheme,macro,r5rs">
<meta property="og:type" content="article">
<meta property="og:title" content="Implementing R5RS&#39;s Macro System: Pattern Language">
<meta property="og:url" content="https://arucil.github.io/2017/r5rs-macro-pattern-language/index.html">
<meta property="og:site_name" content="Plodsoft&#39;s Blog">
<meta property="og:description" content="The pattern language, used in Scheme&amp;#39;s macro transformer specifications, is a convenient tool for writing macros. It makes Scheme users&amp;#39; lives easier, while implementing the pattern language i">
<meta property="og:locale" content="en">
<meta property="og:updated_time" content="2017-11-12T09:44:41.933Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Implementing R5RS&#39;s Macro System: Pattern Language">
<meta name="twitter:description" content="The pattern language, used in Scheme&amp;#39;s macro transformer specifications, is a convenient tool for writing macros. It makes Scheme users&amp;#39; lives easier, while implementing the pattern language i">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://arucil.github.io/2017/r5rs-macro-pattern-language/"/>





  <title>Implementing R5RS's Macro System: Pattern Language | Plodsoft's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Plodsoft's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Programming Language Enthusiast</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-games">
          <a href="/games" rel="section">
            
            Games
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://arucil.github.io/2017/r5rs-macro-pattern-language/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Plodsoft">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars0.githubusercontent.com/u/5410312?v=4&s=460">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Plodsoft's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Implementing R5RS's Macro System: Pattern Language</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-10-10T00:00:00+08:00">
                2017-10-10
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017/r5rs-macro-pattern-language/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2017/r5rs-macro-pattern-language/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>The pattern language, used in Scheme&#39;s macro transformer specifications, is a convenient tool for writing macros. It makes Scheme users&#39; lives easier, while implementing the pattern language is more than a trivial task. In this post I will demonstrate how to implement the pattern language, based on the formal semantics presented in [MBE].<br><a id="more"></a><br>A specific macro expansion is typically divided into two phases, matching and transcription. A macro use is matched against the patterns in the <code>syntax-rules</code> form in order (the matching phase), once a match is found, the template is instantiated accordingly (transcription).<br>A working code is at <a href="https://gist.github.com/arucil/8d533834a312bf7f6a03aa696f3aae3b" target="_blank" rel="external">mbe.scm</a>.</p>
<h1 id="Matching"><a href="#Matching" class="headerlink" title="Matching"></a>Matching</h1><p>When the macro use is matched against a pattern, an environment must be maintained, in which pattern variables are mapped to matched <em>s-exp</em>s. This environment will be used in transcription phase. For example, the macro use <code>(foo a b)</code> matched against <code>(_ e1 e2)</code> yields the environment:<br><figure class="highlight scheme"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">((<span class="name">e1</span> . a)</div><div class="line"> (<span class="name">e2</span> . b))</div></pre></td></tr></table></figure></p>
<p>We used <em>alist</em> here to represent the environment. The first term <code>foo</code> in the macro use was not involved in the matching, so it is not in the resulting environment.<br>When subpatterns with ellipses are involved, things get a bit complicated. We store the list of matched <em>s-exp</em>s in the <code>cdr</code> part of the pair in the environment, with a integer indicating how many ellipses nest the pattern variable (the &quot;level&quot;). For example, <code>(bar a (a 1) (b 2) (c 3))</code> matched against <code>(_ e1 (e2 e3) ...)</code> yields:<br><figure class="highlight scheme"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">((<span class="name">e1</span> . ( <span class="number">0</span> . a ))</div><div class="line"> (<span class="name">e2</span> . ( <span class="number">1</span> . (<span class="name">a</span> b c) ))</div><div class="line"> (<span class="name">e3</span> . ( <span class="number">1</span> . (<span class="name">1</span> <span class="number">2</span> <span class="number">3</span>) )))</div></pre></td></tr></table></figure></p>
<p>We need the level because without it, we can&#39;t prevent users from inadvertently writing macros like this:<br><figure class="highlight scheme"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">(<span class="name"><span class="builtin-name">define-syntax</span></span> foo</div><div class="line">  (<span class="name"><span class="builtin-name">syntax-rules</span></span> ()</div><div class="line">    [(<span class="name">_</span> a) ((<span class="name">a</span>) ...)]))</div><div class="line"></div><div class="line">(<span class="name">foo</span> (<span class="name"><span class="builtin-name">+</span></span> <span class="number">1</span> <span class="number">2</span>))  <span class="comment">; expands to ((+) (1) (2))</span></div></pre></td></tr></table></figure></p>
<p>which is errorneous apparently.<br>Now let&#39;s start the coding part. The function <code>match</code> looks like this:<br><figure class="highlight scheme"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line">(<span class="name"><span class="builtin-name">define</span></span> (<span class="name">match</span> sexp pattern)</div><div class="line">  (<span class="name"><span class="builtin-name">let</span></span> ([<span class="name">env</span> (<span class="name">match-help</span> (<span class="name"><span class="builtin-name">cdr</span></span> sexp) (<span class="name"><span class="builtin-name">cdr</span></span> pattern))])</div><div class="line">    (<span class="name"><span class="builtin-name">if</span></span> env</div><div class="line">      (<span class="name"><span class="builtin-name">map</span></span> (<span class="name"><span class="builtin-name">lambda</span></span> (lv p)</div><div class="line">             (<span class="name"><span class="builtin-name">cons</span></span> (<span class="name"><span class="builtin-name">car</span></span> p)</div><div class="line">                   (<span class="name"><span class="builtin-name">cons</span></span> lv (<span class="name"><span class="builtin-name">cdr</span></span> p))))</div><div class="line">           (<span class="name">get-levels</span> (<span class="name"><span class="builtin-name">cdr</span></span> pattern) <span class="number">0</span>)</div><div class="line">           env))))</div><div class="line"></div><div class="line">(<span class="name"><span class="builtin-name">define</span></span> (<span class="name">get-levels</span> p lv)</div><div class="line">  (<span class="name"><span class="builtin-name">cond</span></span></div><div class="line">   [(<span class="name"><span class="builtin-name">pair?</span></span> p)</div><div class="line">    (<span class="name"><span class="builtin-name">if</span></span> (<span class="name">has-ellipsis?</span> p)</div><div class="line">        (<span class="name"><span class="builtin-name">append</span></span> (<span class="name">get-levels</span> (<span class="name"><span class="builtin-name">car</span></span> p) (<span class="name"><span class="builtin-name">+</span></span> lv <span class="number">1</span>))</div><div class="line">                (<span class="name">get-levels</span> (<span class="name"><span class="builtin-name">cddr</span></span> p) lv))</div><div class="line">        (<span class="name"><span class="builtin-name">append</span></span> (<span class="name">get-levels</span> (<span class="name"><span class="builtin-name">car</span></span> p) lv)</div><div class="line">                (<span class="name">get-levels</span> (<span class="name"><span class="builtin-name">cdr</span></span> p) lv)))]</div><div class="line">   [(<span class="name"><span class="builtin-name">symbol?</span></span> p)</div><div class="line">    (<span class="name"><span class="builtin-name">list</span></span> lv)]</div><div class="line">   [<span class="name"><span class="builtin-name">else</span></span> '()]))</div></pre></td></tr></table></figure></p>
<p>We split the environment into two pieces: a environment without levels and a list of levels. In <code>match-help</code> we construct the former environment, and finally we glue these two pieces together:<br><figure class="highlight scheme"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line">(<span class="name"><span class="builtin-name">define</span></span> (<span class="name">match-help</span> sexp pattern)</div><div class="line">  (<span class="name"><span class="builtin-name">call/cc</span></span></div><div class="line">   (<span class="name"><span class="builtin-name">lambda</span></span> (k)</div><div class="line">     (<span class="name"><span class="builtin-name">define</span></span> (<span class="name">fail</span>)</div><div class="line">       (<span class="name">k</span> <span class="literal">#f</span>))</div><div class="line"></div><div class="line">     (<span class="name"><span class="builtin-name">let</span></span> rec ([<span class="name">sexp</span> sexp] [<span class="name">pattern</span> pattern])</div><div class="line">       (<span class="name"><span class="builtin-name">cond</span></span></div><div class="line">        [(<span class="name"><span class="builtin-name">symbol?</span></span> pattern)</div><div class="line">         (<span class="name"><span class="builtin-name">list</span></span> (<span class="name"><span class="builtin-name">cons</span></span> pattern sexp))]</div><div class="line">        [(<span class="name"><span class="builtin-name">pair?</span></span> pattern)</div><div class="line">         (<span class="name"><span class="builtin-name">if</span></span> (<span class="name">has-ellipsis?</span> pattern)</div><div class="line">             ...</div><div class="line">             (<span class="name"><span class="builtin-name">if</span></span> (<span class="name"><span class="builtin-name">pair?</span></span> sexp)</div><div class="line">                 (<span class="name"><span class="builtin-name">append</span></span> (<span class="name">rec</span> (<span class="name"><span class="builtin-name">car</span></span> sexp) (<span class="name"><span class="builtin-name">car</span></span> pattern))</div><div class="line">                         (<span class="name">rec</span> (<span class="name"><span class="builtin-name">cdr</span></span> sexp) (<span class="name"><span class="builtin-name">cdr</span></span> pattern)))</div><div class="line">                 (<span class="name">fail</span>)))]</div><div class="line">        [<span class="name"><span class="builtin-name">else</span></span></div><div class="line">         (<span class="name"><span class="builtin-name">if</span></span> (<span class="name"><span class="builtin-name">eqv?</span></span> pattern sexp)</div><div class="line">             '()</div><div class="line">             (<span class="name">fail</span>))])))))</div><div class="line"></div><div class="line">(<span class="name"><span class="builtin-name">define</span></span> (<span class="name">has-ellipsis?</span> p)</div><div class="line">  (<span class="name"><span class="builtin-name">and</span></span> (<span class="name"><span class="builtin-name">pair?</span></span> (<span class="name"><span class="builtin-name">cdr</span></span> p))</div><div class="line">       (<span class="name"><span class="builtin-name">eq?</span></span> <span class="symbol">'...</span> (<span class="name"><span class="builtin-name">cadr</span></span> p))))</div></pre></td></tr></table></figure></p>
<p>Matching patterns without following ellipsis is trivial. When the pattern is a symbol, we construct a environment with one entry. When a ordinary pair is encountered, we <code>append</code> the two subenvironments resulted from matching <code>car</code> and <code>cdr</code> of the pair. We use <code>eqv?</code> to compare the pattern with the s-<em>exp</em> in other cases.<br>Major difficulty lies in matching patterns with following ellipsis. Following code is what we omitted at line 13 above:<br><figure class="highlight scheme"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line">(<span class="name"><span class="builtin-name">let</span></span> loop ([<span class="name">sexp</span> sexp] [<span class="name">env*</span> '()])</div><div class="line">  (<span class="name"><span class="builtin-name">let</span></span> ([<span class="name">env</span> (<span class="name"><span class="builtin-name">if</span></span> (<span class="name"><span class="builtin-name">pair?</span></span> sexp)</div><div class="line">                 (<span class="name">match-help</span> (<span class="name"><span class="builtin-name">car</span></span> sexp) (<span class="name"><span class="builtin-name">car</span></span> pattern))</div><div class="line">                 <span class="literal">#f</span>)])</div><div class="line">    (<span class="name"><span class="builtin-name">if</span></span> env</div><div class="line">        (<span class="name">loop</span> (<span class="name"><span class="builtin-name">cdr</span></span> sexp)</div><div class="line">              (<span class="name"><span class="builtin-name">cons</span></span> (<span class="name"><span class="builtin-name">map</span></span> cdr env) <span class="comment">; removing name part in env</span></div><div class="line">                    env*))</div><div class="line">        (<span class="name"><span class="builtin-name">append</span></span> (<span class="name"><span class="builtin-name">apply</span></span> map</div><div class="line">                       list</div><div class="line">                       (<span class="name">get-pattern-variables</span> (<span class="name"><span class="builtin-name">car</span></span> pattern))</div><div class="line">                       (<span class="name"><span class="builtin-name">reverse</span></span> env*))</div><div class="line">                (<span class="name">rec</span> sexp (<span class="name"><span class="builtin-name">cddr</span></span> pattern))))))</div></pre></td></tr></table></figure></p>
<p>We keep matching the subpattern until the matching failed, collecting subenvironments along the way. Finally we combine all these subenvironments into one, in which every pattern variable maps to a list of matched s-<em>exp</em>s. Note that R5RS stipulates that ellipsis-ed patterns are only allowed to occur at the tail of a list, but we augment the syntax, allowing ellipsis-ed patterns to occur in the middle of a list, which is similar to a feature introduced in <a href="https://srfi.schemers.org/srfi-46/srfi-46.html" target="_blank" rel="external">SRFI46</a>.<br>The helper function <code>get-pattern-variables</code> occured in above code is following.<br><figure class="highlight scheme"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">(<span class="name"><span class="builtin-name">define</span></span> (<span class="name">get-pattern-variables</span> p)</div><div class="line">  (<span class="name"><span class="builtin-name">cond</span></span></div><div class="line">   [(<span class="name"><span class="builtin-name">pair?</span></span> p)</div><div class="line">    (<span class="name"><span class="builtin-name">if</span></span> (<span class="name">has-ellipsis?</span> p)</div><div class="line">        (<span class="name"><span class="builtin-name">append</span></span> (<span class="name">get-pattern-variables</span> (<span class="name"><span class="builtin-name">car</span></span> p))</div><div class="line">                (<span class="name">get-pattern-variables</span> (<span class="name"><span class="builtin-name">cddr</span></span> p)))</div><div class="line">        (<span class="name"><span class="builtin-name">append</span></span> (<span class="name">get-pattern-variables</span> (<span class="name"><span class="builtin-name">car</span></span> p))</div><div class="line">                (<span class="name">get-pattern-variables</span> (<span class="name"><span class="builtin-name">cdr</span></span> p))))]</div><div class="line">   [(<span class="name"><span class="builtin-name">symbol?</span></span> p)</div><div class="line">    (<span class="name"><span class="builtin-name">list</span></span> p)]</div><div class="line">   [<span class="name"><span class="builtin-name">else</span></span> '()]))</div></pre></td></tr></table></figure></p>
<h1 id="Transcription"><a href="#Transcription" class="headerlink" title="Transcription"></a>Transcription</h1><p>The environment we got from <code>match</code> would be handed to <code>transcribe</code> to get final expanded form.<br><figure class="highlight scheme"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line">(<span class="name"><span class="builtin-name">define</span></span> (<span class="name">transcribe</span> template env)</div><div class="line">  (<span class="name"><span class="builtin-name">let-values</span></span> ([(<span class="name">env/lv0</span> env/lv+)</div><div class="line">                (<span class="name">split-env</span> env)])</div><div class="line">    (<span class="name">transcribe-help</span> template env/lv0 env/lv+)))</div><div class="line"></div><div class="line">(<span class="name"><span class="builtin-name">define</span></span> (<span class="name">split-env</span> env)</div><div class="line">  (<span class="name">partition</span> (<span class="name"><span class="builtin-name">lambda</span></span> (p) (<span class="name"><span class="builtin-name">zero?</span></span> (<span class="name"><span class="builtin-name">cadr</span></span> p))) env))</div><div class="line"></div><div class="line">(<span class="name"><span class="builtin-name">define</span></span> (<span class="name">transcribe-help</span> template env/lv0 env/lv+)</div><div class="line">  (<span class="name"><span class="builtin-name">cond</span></span></div><div class="line">    [(<span class="name"><span class="builtin-name">symbol?</span></span> template)</div><div class="line">     (<span class="name"><span class="builtin-name">cond</span></span></div><div class="line">       [(<span class="name"><span class="builtin-name">assq</span></span> template env/lv0) =&gt; cddr]</div><div class="line">       [(<span class="name"><span class="builtin-name">assq</span></span> template env/lv+)</div><div class="line">        (<span class="name">wrong</span> <span class="string">"Too few ellipses with"</span> template)]</div><div class="line">       [<span class="name"><span class="builtin-name">else</span></span> template])]</div><div class="line">    [(<span class="name"><span class="builtin-name">pair?</span></span> template)</div><div class="line">     (<span class="name"><span class="builtin-name">if</span></span> (<span class="name">has-ellipsis?</span> template)</div><div class="line">       ...</div><div class="line">       (<span class="name"><span class="builtin-name">cons</span></span> (<span class="name">transcribe-help</span> (<span class="name"><span class="builtin-name">car</span></span> template) env/lv0 env/lv+)</div><div class="line">             (<span class="name">transcribe-help</span> (<span class="name"><span class="builtin-name">cdr</span></span> template) env/lv0 env/lv+)))]</div><div class="line">    [<span class="name"><span class="builtin-name">else</span></span> template]))</div></pre></td></tr></table></figure></p>
<p>Before actual transcription begins, we split the environment into two subenvironments, one environment of patterns with level zero, the other with non-zero level.<br>When the template is a symbol, we first check if this symbol occurs in the level-zero environment, and replace this symbol with corresponding s-<em>exp</em> if it does. If it doesn&#39;t occur in both environments, it&#39;s considered a literal name, and will be left as it is. Transcribing other ellipsis-less templates is easy, as you can see.<br>In order to transcribe ellipsis-ed templates, we need to reverse what was done in <code>match</code>, as shown in following code.<br><figure class="highlight scheme"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div></pre></td><td class="code"><pre><div class="line">(<span class="name"><span class="builtin-name">let*</span></span> ([<span class="name">free-variables</span> (<span class="name">get-pattern-variables</span> (<span class="name"><span class="builtin-name">car</span></span> template))]</div><div class="line">       [<span class="name">new-env/lv+</span> (<span class="name">filter</span> (<span class="name"><span class="builtin-name">lambda</span></span> (x)</div><div class="line">                              (<span class="name"><span class="builtin-name">memq</span></span> (<span class="name"><span class="builtin-name">car</span></span> x) free-variables))</div><div class="line">                            env/lv+)])</div><div class="line">  (<span class="name"><span class="builtin-name">if</span></span> (<span class="name"><span class="builtin-name">null?</span></span> new-env/lv+)</div><div class="line">      (<span class="name">wrong</span> <span class="string">"Too many ellipses"</span>)</div><div class="line">      (<span class="name"><span class="builtin-name">let</span></span> ([<span class="name">names</span> (<span class="name"><span class="builtin-name">map</span></span> car new-env/lv+)]</div><div class="line">            [<span class="name">levels</span> (<span class="name"><span class="builtin-name">map</span></span> (<span class="name"><span class="builtin-name">lambda</span></span> (x)</div><div class="line">                           (<span class="name"><span class="builtin-name">-</span></span> (<span class="name"><span class="builtin-name">cadr</span></span> x) <span class="number">1</span>))</div><div class="line">                         new-env/lv+)]</div><div class="line">            [<span class="name">sexpss</span> (<span class="name"><span class="builtin-name">map</span></span> cddr new-env/lv+)])</div><div class="line">        (<span class="name"><span class="builtin-name">if</span></span> (<span class="name"><span class="builtin-name">apply</span></span> = (<span class="name"><span class="builtin-name">map</span></span> length sexpss))</div><div class="line">            (<span class="name"><span class="builtin-name">let</span></span> ([<span class="name">envs</span> (<span class="name"><span class="builtin-name">apply</span></span> map</div><div class="line">                               (<span class="name"><span class="builtin-name">lambda</span></span> <span class="name">sexps</span></div><div class="line">                                 (map (lambda (name level sexp)</div><div class="line">                                        (<span class="name"><span class="builtin-name">cons</span></span> name</div><div class="line">                                              (<span class="name"><span class="builtin-name">cons</span></span> level sexp)))</div><div class="line">                                      names levels sexps))</div><div class="line">                               sexpss)])</div><div class="line">              (<span class="name"><span class="builtin-name">append</span></span> (<span class="name"><span class="builtin-name">map</span></span> (<span class="name"><span class="builtin-name">lambda</span></span> (env)</div><div class="line">                             (<span class="name"><span class="builtin-name">let-values</span></span> ([(<span class="name">new-env/lv0</span> env/lv+)</div><div class="line">                                           (<span class="name">split-env</span> env)])</div><div class="line">                               (<span class="name">transcribe-help</span> (<span class="name"><span class="builtin-name">car</span></span> template)</div><div class="line">                                                (<span class="name"><span class="builtin-name">append</span></span> new-env/lv0 env/lv0)</div><div class="line">                                                env/lv+)))</div><div class="line">                      envs)</div><div class="line">                     (<span class="name">transcribe-help</span> (<span class="name"><span class="builtin-name">cddr</span></span> template) env/lv0 env/lv+)))</div><div class="line">            (<span class="name">wrong</span> <span class="string">"Unequal length"</span>)))))</div></pre></td></tr></table></figure></p>
<p>First we get all pattern variables occuring in the template with non-zero level. If there is no such variable, we can&#39;t determine how many times the template should be repeated. Then we must assure these pattern variables map to equal-length lists of s-<em>exp</em>s. Next, we decompose these lists and construct new environments separately, with levels decremented. Last, <code>transcribe-help</code> is invoked on these environments. That gets the transcription repetition done.<br>Note that we must carry the level-zero environment all the way, so following expansion correctly works.<br><figure class="highlight scheme"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">(<span class="name"><span class="builtin-name">define-syntax</span></span> foo</div><div class="line">  (<span class="name"><span class="builtin-name">syntax-rules</span></span> ()</div><div class="line">    [(<span class="name">_</span> e1 e2 ...) ((<span class="name">e1</span> e2) ...)]))</div><div class="line"></div><div class="line">(<span class="name">foo</span> <span class="number">1</span> a b c) <span class="comment">; expands to following form</span></div><div class="line">((<span class="name">1</span> a) (<span class="name">1</span> b) (<span class="name">1</span> c))</div></pre></td></tr></table></figure></p>
<p>That&#39;s all fow now. Another interesting characteristic of macro, hygiene, which I didn&#39;t cover in this post, would be discussed in future posts.</p>
<h1 id="Bibliography"><a href="#Bibliography" class="headerlink" title="Bibliography"></a>Bibliography</h1><p><strong>[MBE]</strong> <em>Macro-by-example</em>, Eugene Kohlbecker, et al</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Scheme/" rel="tag"># Scheme</a>
          
            <a href="/tags/Macro/" rel="tag"># Macro</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/dynamic-wind-implementation/" rel="prev" title="dynamic-wind的实现">
                dynamic-wind的实现 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>
  


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://avatars0.githubusercontent.com/u/5410312?v=4&s=460"
                alt="Plodsoft" />
            
              <p class="site-author-name" itemprop="name">Plodsoft</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          <div class="links-of-author motion-element">
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Matching"><span class="nav-number">1.</span> <span class="nav-text">Matching</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Transcription"><span class="nav-number">2.</span> <span class="nav-text">Transcription</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Bibliography"><span class="nav-number">3.</span> <span class="nav-text">Bibliography</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Plodsoft</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.3</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  

    
      <script id="dsq-count-scr" src="https://plodsoft.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'https://arucil.github.io/2017/r5rs-macro-pattern-language/';
          this.page.identifier = '2017/r5rs-macro-pattern-language/';
          this.page.title = 'Implementing R5RS\'s Macro System: Pattern Language';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://plodsoft.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  










  





  

  

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
